package handler

import (
	"github.com/gin-gonic/gin"
	"github.com/lab-online/internal/course/constant"
	"github.com/lab-online/internal/course/entity"
	mw "github.com/lab-online/pkg/middleware"
	"github.com/lab-online/pkg/resp"
	"github.com/lab-online/pkg/util"
)

type searchCourseReqQuery struct {
	ID   uint   `form:"id" binding:"omitempty,min=1" example:"1"`             // 课程ID
	Name string `form:"name" binding:"omitempty,min=1,max=10" example:"高等数学"` // 课程名称
}

var SearchCourseValidator = mw.NewValidator(func() *mw.ValidatorOptions {
	return &mw.ValidatorOptions{
		Query: &searchCourseReqQuery{},
	}
})

type SearchCourseRespData struct {
	ID          uint   `json:"id" binding:"required"`          // 课程ID
	Name        string `json:"name" binding:"required"`        // 课程名称
	Description string `json:"description" binding:"required"` // 课程描述
}

type SearchCourseRespBody struct {
	resp.BaseRespBody
	Data []SearchCourseRespData `json:"data" binding:"required"`
}

// SearchCourse 搜索课程
//
//	@Summary				搜索课程
//	@Description.markdown	SearchCourse
//	@Tags					course
//	@Accept					json
//	@Produce				json
//	@Security				bearer
//	@Param					Authorization	header		string					true	"`all`"
//	@Param					class			query		searchCourseReqQuery	true	"课程信息"
//	@Success				200				{object}	SearchCourseRespBody
//	@Failure				400				{object}	resp.FailedRespBodyString
//	@x-apifox-status		"developing"
//	@Router					/v1/courses	[get]
func (h *Handler) SearchCourse(c *gin.Context) {
	query := c.MustGet(mw.KeyQuery).(*searchCourseReqQuery)
	queryEntity := entity.NewCourseEntity(
		entity.WithID(query.ID),
		entity.WithName(query.Name),
	)

	if courses, err := h.domain.SearchCourse(queryEntity); err != nil {
		resp.ErrorHandler(c, err)
	} else {
		resp.Success(c, constant.CodeSearchCourseSuccess, util.SliceMap(courses,
			func(course entity.CourseEntity) *SearchCourseRespData {
				return &SearchCourseRespData{
					ID:          course.GetID(),
					Name:        course.GetName(),
					Description: course.GetDescription(),
				}
			}),
		)
	}
}
